import { BrowserWindow, app } from 'electron';
import { ipcHelper } from '@electron-toolkit/utils';
import { RcWindowChange, RcOpenChildWindow } from '#common/types/event';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { createTray, destroyTray } from '../../widgets/tray';
import { getUserDataStore } from '$main/utils/store';
import { createChildWindow } from '$main/windows/child-window';
import { sendWebContentsEvent } from '.';
import {
  openSelectDirectoryDialog,
  openSelectDirectoryDialogSync,
  openSelectVideosDialog
} from '$main/utils/dialog';
import {
  getFileInDirectory,
  readFileContentAsync,
  readFileStream,
  readFileBuffer,
  readFileBlob,
  getVideoMetadata,
  writeFileReplace
} from '$main/utils/fs';
import type { GetFile, GetFileRes } from '#common/types/file';
import path from 'path';

//窗体间通信
export function initialCommonWindowIPC() {
  ipcHelper.on('rc:window-change', (event, action: RcWindowChange['action']) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    if (!win) {
      return;
    }
    if (action === 'max') {
      const isMaximized = win.isMaximized();
      if (isMaximized) {
        win.unmaximize();
      } else {
        win.maximize();
        win.focus();
      }
      return;
    }
    if (action === 'min') {
      win.minimize();
      return;
    }
  });

  ipcHelper.on('rc:win-action', (event, action: string, data: any) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    if (!win) {
      return;
    }

    if (action === 'setSize') {
      win.setSize(data.width, data.height);
      return;
    }

    if (action === 'setResizable') {
      win.setResizable(data);
      return;
    }

    if (action === 'setAlwaysOnTop') {
      win.setAlwaysOnTop(data);
      return;
    }

    if (action === 'center') {
      win.center();
      return;
    }

    if (action === 'setMinimumSize') {
      win.setMinimumSize(data.width, data.height);
      return;
    }
    if (action === 'setOpacity') {
      win.setOpacity(data);
      return;
    }

    if (action === 'show') {
      win.show();
      return;
    }

    if (action === 'restore') {
      win.restore();
      return;
    }

    if (action === 'minimize') {
      win.minimize();
      return;
    }

    if (action === 'maximize') {
      win.maximize();
      return;
    }

    if (action === 'focus') {
      win.focus();
      return;
    }
  });

  ipcHelper.on('rc:exit-app', () => {
    app.exit();
  });

  ipcHelper.on('rc:openDevTools', (event) => {
    BrowserWindow.fromWebContents(event.sender)?.webContents.toggleDevTools();
  });

  ipcHelper.on('rc:app-tray', (event, show: boolean) => {
    show ? createTray() : destroyTray();
  });

  ipcHelper.on('rc:childWindow', (event, action: string, param: RcOpenChildWindow) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    if (win == null) {
      return;
    }

    if (action == 'open') {
      if (win.getChildWindows().some((x) => x.title == param.title)) return;

      createChildWindow(win, {
        title: param.title,
        width: param.width,
        height: param.height,
        url: param.url
      });
    }

    const parentWin = win.getParentWindow();
    if (action == 'close' || action == 'logout') {
      win.close();
      parentWin?.show();

      if (action == 'logout' && parentWin) {
        sendWebContentsEvent(parentWin.webContents, 'reply:rc:logout', 'logout');
      }
    }
  });

  //同步
  ipcHelper.handle('rc:select-folder', async () => {
    return await openSelectDirectoryDialog();
  });
  ipcHelper.handle('rc:select-videos', async () => {
    return await openSelectVideosDialog();
  });

  ipcHelper.handle(
    'rc:read-file-content',
    async (_, { directory, fileName, readType = 'Text' }: GetFile) => {
      const filePath = await getFileInDirectory(directory, fileName!);
      if (!filePath) {
        console.log('文件不存在');
        return null;
      }
      try {
        switch (readType) {
          case 'Stream':
            return { type: readType, data: await readFileStream(filePath) } satisfies GetFileRes;
          case 'Blob':
            return { type: readType, data: await readFileBlob(filePath) } satisfies GetFileRes;
          case 'Buffer':
            return { type: readType, data: readFileBuffer(filePath) } satisfies GetFileRes;
          default:
            return {
              type: readType,
              data: await readFileContentAsync(filePath)
            } satisfies GetFileRes;
        }
      } catch (error) {
        console.error('读取文件错误:', error);
        throw error;
      }
    }
  );

  ipcHelper.handle('rc:read-video-mete', async (_, filePath: string) => {
    const parsed = path.parse(filePath);
    if (!(await getFileInDirectory(parsed.dir, parsed.base))) {
      console.log('文件不存在');
      return null;
    }

    try {
      return await getVideoMetadata(filePath);
    } catch (error) {
      console.error('读取文件错误:', error);
      throw error;
    }
  });

  ipcHelper.handle('rc:write-fileReplace-sync', (_, { directory, fileName, content }) => {
    return writeFileReplace(directory, fileName, content);
  });

  //异步
  ipcHelper.on('rc:select-folder-sync', () => {
    return openSelectDirectoryDialogSync();
  });

  ipcHelper.on('rc:router-page-data-change', (e, routeName: string[]) => {
    const win = BrowserWindow.fromWebContents(e.sender);
    const parentWin = win?.getParentWindow();
    if (!parentWin) return;

    sendWebContentsEvent(parentWin.webContents, 'reply:rc:router-page-data-change', routeName);
  });
}

export function onCommonWindowEvent(window: BrowserWindow) {
  window.on('maximize', () => {
    const isLoginPage = getUserDataStore().get('tokenData');
    if (!isLoginPage) return;

    window.webContents.send('reply:rc:window-change', {
      action: 'max',
      maxState: true
    } satisfies RcWindowChange);
  });

  window.on('unmaximize', () => {
    const isLoginPage = getUserDataStore().get('tokenData');
    if (!isLoginPage) return;

    window.webContents.send('reply:rc:window-change', {
      action: 'max',
      maxState: false
    } satisfies RcWindowChange);
  });

  window.on('minimize', () => {
    const isLoginPage = getUserDataStore().get('tokenData');
    if (!isLoginPage) return;

    window.webContents.send('reply:rc:window-change', {
      action: 'min'
    } satisfies RcWindowChange);
  });
}
